import pyautogui as pyg
import pygetwindow as gw
import keyboard
import time 
import os
import pyscreeze
import Zengfu
# 调整窗口大小 800*600
# 窗口对齐左上角防止
# 装备防止第一格
# 其他装备先强化一次，加速增幅
# --------------------------
# 坐标不对，使用点击坐标获取工具自己调整 
# 自己安装依赖组件
# pip install pyautogui
# pip install keyboard
# 打包方法 pyinstaller.exe --onefile --add-data "image:image"  龙服-辅助.py
pause=True 
BH_LIMIT=100
SUCCESS_LIMIT=3
HAS_SUCCESS_LIMIT=0
zengfu_count=0

STATUS_FIND_CLICK = 101  # 找到图片并点击
STATUS_FIND = 102  # 只找图片
STATUS_NOT_IMG = 104  # 图片不存在
STATUS_NOT_FOUND = 404  # 没找到图片

SUCCESS_IMAGE=os.path.join(os.path.join(os.path.dirname(__file__),"image"),"duanzao_success.png")
SUCCESS_IMAGE_NOT_ME=os.path.join(os.path.join(os.path.dirname(__file__),"image"),"not_me_success.png")
FAIL_COMMIT_IMAGE=os.path.join(os.path.join(os.path.dirname(__file__),"image"),"baohu_commit.png")
DNF_WD = gw.getWindowsWithTitle("Dungeon & Fighter")[0]



# 识图封装 300找图,，点一次，相似度0.9，像素步长5,不灰度
def find_img_click(path, count=10, clicks=0, confidence=0.9, region=(0, 170, 1280, 730), grayscale=False, step=5):
    if not os.path.exists(path):
        print(f"文件 {path.split('/')[-1]} 不存在")
        return STATUS_NOT_IMG
    attempts = 1
    while attempts < count+1:
        try:
            start_time = time.time()
            point = pyg.locateCenterOnScreen(
                path, confidence=confidence, region=region, grayscale=grayscale, step=step)
            if point is not None and clicks:
                for _ in range(clicks):
                    pyg.click(point)
                    time.sleep(0.1)
                click_time = time.time()
                print(
                    f"第{attempts}次 {path.split('/')[-1]} 识别成功,点击{clicks}次 耗时{click_time-start_time:.3f}")
                return STATUS_FIND_CLICK
            elif point is not None and clicks == 0:
                end_time = time.time()
                #print(
                #    f"第{attempts}次 {path.split('/')[-1]} 识别成功 无点击耗时{end_time-start_time:.3f}")
                return STATUS_FIND
        except pyg.ImageNotFoundException:
            not_find_time = time.time()
            #print(
            #    f"第{attempts}次 {path.split('/')[-1]} 识别失败 耗时{not_find_time-start_time:.3f}")
        attempts += 1
    if count == 300:
        print("未发现图片")
    return STATUS_NOT_FOUND
#gw.activate()
print(f"title:{DNF_WD}")
INIT_WIDTH=800
INIT_HEIGHT=600
def compute_position(x_offset,y_offset):
    y= DNF_WD.top+(INIT_HEIGHT/2+y_offset)*(DNF_WD.height/INIT_HEIGHT)
    x= DNF_WD.left+(INIT_WIDTH/2+x_offset)*(DNF_WD.width/INIT_WIDTH)
    return (x,y)
def get_position():
    try:
        # 获取当前鼠标的坐标
        x, y = pyg.position()
        print(f"Mouse position: X={x}, Y={y}")
        time.sleep(1)
    except KeyboardInterrupt:
        print("Program terminated.")

def click_dnf(x,y):
    pyg.moveTo(x,y,duration=0.3)
    pyg.mouseDown(button="left")
    pyg.mouseUp(button="left")

def pause_zengfu():
    global pause 
    pause =  True
    print("暂停增福")
def start_zengfu():
    global pause 
    pause =  False
    print("开始增福")

def zengfu():
    global pause
    global HAS_SUCCESS_LIMIT
    global SUCCESS_LIMIT
    #增幅按钮位置
    if HAS_SUCCESS_LIMIT >= SUCCESS_LIMIT:
        print(f"已经成功增幅次数：{HAS_SUCCESS_LIMIT},最大次数限制：{SUCCESS_LIMIT},增幅次数：{zengfu_count}")
        print(f"请按ctrl+F12重置增幅成功次数")
        pause = True
        return
    (x,y)=compute_position(-110,55)
    click_dnf(x,y)
    #移动到装备第一格
    (x,y)=compute_position(85,-10)
    click_dnf(x,y)
    # 确认增幅 X=371, Y=383 
    (x,y)=compute_position(-30,85)
    click_dnf(x,y)
    # 保护卷确认
    (x,y)=compute_position(-30,50)
    click_dnf(x,y)
    time.sleep(2.0)
    is_success =  find_img_click(SUCCESS_IMAGE, count=5,region=(DNF_WD.left,DNF_WD.top,DNF_WD.left + DNF_WD.width, DNF_WD.top+DNF_WD.height))
    if is_success != STATUS_FIND:
        is_success = find_img_click(SUCCESS_IMAGE_NOT_ME,count=5,region=(DNF_WD.left,DNF_WD.top,DNF_WD.left + DNF_WD.width, DNF_WD.top+DNF_WD.height))
    if is_success == STATUS_FIND:
        print(f"增幅成功！,成功图片发现结果：{is_success}")
        HAS_SUCCESS_LIMIT=HAS_SUCCESS_LIMIT+1

    #失败确认位置 410 350
    (x,y)=compute_position(0,30)
    click_dnf(x,y)
    # 失败确认位置2 406, Y=352
    (x,y)=compute_position(5,40)
    click_dnf(x,y)
    time.sleep(0.5)



def reset_success():
    global BH_LIMIT
    global SUCCESS_LIMIT
    global zengfu_count
    global HAS_SUCCESS_LIMIT
    tmp_succ_limit_str=input(f"请输入增幅成功次数，默认{SUCCESS_LIMIT}直接回车：")
    if tmp_succ_limit_str != '':
        SUCCESS_LIMIT = int(tmp_succ_limit_str)
    print(f"增幅最大成功次数为：{SUCCESS_LIMIT}")
    HAS_SUCCESS_LIMIT=0
    print(f"当前保护卷数据量为{BH_LIMIT} ,增幅次数为{zengfu_count},增幅已成功次数{HAS_SUCCESS_LIMIT}，增幅最大成功次数{SUCCESS_LIMIT}")

def reset_bh():
    global BH_LIMIT
    global zengfu_count
    global HAS_SUCCESS_LIMIT
    global SUCCESS_LIMIT
    tmp_bh_limit_str=input("请输入增幅次数，默认直接回车：")
    if tmp_bh_limit_str != '':
        BH_LIMIT = int(tmp_bh_limit_str)
    print(f"增幅次数为：{BH_LIMIT}")
    zengfu_count=0
    print(f"当前保护卷数据量为{BH_LIMIT} ,增幅次数为{zengfu_count},增幅已成功次数{HAS_SUCCESS_LIMIT}，增幅最大成功次数{SUCCESS_LIMIT}")
    #reset_success()    

keyboard.add_hotkey("ctrl+f9",start_zengfu)
keyboard.add_hotkey("ctrl+f10",pause_zengfu)
keyboard.add_hotkey("ctrl+f11",reset_bh)
keyboard.add_hotkey("ctrl+f12", reset_success)
print("""
！！！！！！！！！！免责声明！！！！！！！！！！
！！使用本程序增幅误操作导致装备损坏概不负责！！
！！不赔的哦！真不赔的哦！不要到时候又来找哦！！
！！！！！！！！！！！！！！！！！！！！！！！！
""")
print("================增幅设置====================")
print(f"增幅次数：默认{BH_LIMIT}次")
reset_bh()
reset_success()
print("================增幅提示(默认增幅100次停止)====================")
print("1,请按ctrl+f9开始 ，ctrl+f10停止增幅， ctrl+f11 重新设置增幅次数,ctrl+f12 增幅成功次数")
print("2.装备放置第一格")
print("3.其他装备先强化一次，加速增幅")
print("4.打开增幅界面")
print("5.按ctrl+f9开始增幅")
print("6.按ctrl+f10停止增幅")
print("！！！！！！！！！！！！！！高阶的保护卷也放相当量在包里，，别增幅上去了，结果保护卷等级不够，导致装备碎了")
while True:
    if pause :
        time.sleep(1)
    elif zengfu_count >= BH_LIMIT:
        print(f"增幅次数{zengfu_count},保护次数为{BH_LIMIT},超过保护卷个数,增幅已经暂停")
        print(f"请按ctrl+f11,根据情况设置保护卷个数")
        pause = True
    else:
        # 增幅开关
        zengfu_count+=1
        print(f"增幅次数{zengfu_count}")
        zengfu()

        